package com.itzdm.message.advice;

import com.itzdm.common.advice.CommonExceptionAdvice;
import com.itzdm.common.constant.MessageConstant;
import com.itzdm.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.net.ConnectException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLSyntaxErrorException;

@RestControllerAdvice
@Slf4j
public class MessageExceptionAdvice extends CommonExceptionAdvice {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<?> handleSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e) {
        String message = e.getMessage();
        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String username = split[2];
            String msg = username + MessageConstant.ALREADY_EXISTS;
            return Result.error(msg);
        } else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }

    @ExceptionHandler(SQLSyntaxErrorException.class)
    public Result<?> handleSQLSyntaxErrorException(SQLSyntaxErrorException e) {
        log.error("数据库语法错误: {}", e.getMessage());
        return Result.error(MessageConstant.MYSQL_ERROR);
    }

    @ExceptionHandler(ConnectException.class)
    public Result<?> handleConnectException(ConnectException e) {
        log.error("连接异常: {}", e.getMessage());
        return Result.error(MessageConstant.CONNECT_ERROR);
    }
} 